<?php
class catalog_model extends CI_Model {
    public function __construct() {
        parent::__construct();
    }

    public function getSong($id) {
        $query = $this -> db -> where(array("song_id" => $id)) -> get('songs');
        return $query->result();
    }

    public function get_song_names() {
        $res = $this -> db ->select('song_id,name')-> get('songs');
        return $res->result();
    }

    public function saveSong($data) {
        $f_data = $this -> formatInput($data);
        $q = array();
        if (isset($data['song_id'])) { 
            $q = $this -> db -> set($f_data) -> where(array("_id" => $data['song_id'])) -> update("songs");
        } else {
            $q = $this -> db -> insert('songs', $f_data);
        }
        return $q;
    }

    private function formatInput($data) {
        $formated_data = $data;
        unset($formated_data['song_id']);
        $formated_data['name'] = trim($data['name']);
        $formated_data['artist'] = trim($data['artist']);
        $formated_data['genre'] = trim($data['genre']);
        if (!isset($data['song_id'])) {
            $formated_data['added_on'] = date('Y-m-d H:i:s'); 
        } else {
            $formated_data['updated_on'] = date('Y-m-d H:i:s'); 
        }
        return $formated_data;
    }

}
